package com.vben.ai.config;

import com.vben.ai.playground.entity.PlaygroundScore;
import com.vben.ai.playground.service.PlaygroundScoreService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.core.NestedExceptionUtils;

import java.math.BigDecimal;
import java.util.function.Function;

@Configuration
@Slf4j
public class EduAssistantTools {

    @Resource
    private PlaygroundScoreService playgroundScoreService;

    public record AddScoreRequest(String code, String name, BigDecimal chinese, BigDecimal math, BigDecimal english) {

    }

    public record AddScoreResponse(Boolean result) {

    }

    public record GetScoreRequest(String code, String name) {

    }

    public record GetScoreResponse(PlaygroundScore score) {

    }

    @Bean
    @Description("录入成绩")
    public Function<AddScoreRequest, AddScoreResponse> addScore() {
        return request -> {
            try {
                PlaygroundScore score = new PlaygroundScore();
                score.setCode(request.code());
                score.setName(request.name());
                score.setChinese(request.chinese());
                score.setMath(request.math());
                score.setEnglish(request.english());
                System.out.println("录入成绩：" + score);
                return new AddScoreResponse(playgroundScoreService.save(score));
            } catch (Exception e) {
                log.warn("add score: {}", NestedExceptionUtils.getMostSpecificCause(e).getMessage());
                return new AddScoreResponse(false);
            }
        };
    }

    @Bean
    @Description("查询成绩")
    public Function<GetScoreRequest, GetScoreResponse> getScore() {
        return request -> {
            try {
                String code = request.code();
                String name = request.name();
                PlaygroundScore score = playgroundScoreService
                        .lambdaQuery()
                        .eq(PlaygroundScore::getCode, code)
                        .eq(PlaygroundScore::getName, name)
                        .one();
                return new GetScoreResponse(score);
            } catch (Exception e) {
                log.warn("get score: {}", NestedExceptionUtils.getMostSpecificCause(e).getMessage());
                return null;
            }
        };
    }


}
